package com.alibaba.dubbo.remoting.transport.netty4;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.dubbo.common.configure.ExtensionConfiguratorUtils;
import com.alibaba.dubbo.remoting.buffer.ChannelBuffer;

public abstract class AbstractNetty4ChannelBuffer implements
com.alibaba.dubbo.remoting.buffer.ChannelBuffer{
	protected List<Component> components;
	static protected int defaultBlockSize = 1024;
	static{
		defaultBlockSize = ExtensionConfiguratorUtils.getInstance().getIntValue("com.alibaba.dubbo.remoting.transport.netty4.blockSize", 1024);		
	}

	public AbstractNetty4ChannelBuffer() {
		super();
		components = new ArrayList<Component>();
	}

	protected int getComponentIndex(int offset) {
		int low = 0;
		int count = this.components.size();
		for (int high = count; low <= high;) {
			int mid = low + high >>> 1;
			if(mid >= count) break;
			Component c = (Component) this.components.get(mid);
			if (offset >= c.endOffset) {
				low = mid + 1;
			} else if (offset < c.offset) {
				high = mid - 1;
			} else {
				return mid;
			}
		}
		return -1;
	}

	protected Component getComponent(int offset) {
		int low = 0;
		int count = this.components.size();
		for (int high = count; low <= high;) {
			int mid = low + high >>> 1;
			if(mid >= count) break;
			Component c = (Component) this.components.get(mid);
			if (offset >= c.endOffset) {
				low = mid + 1;
			} else if (offset < c.offset) {
				high = mid - 1;
			} else {
				assert (c.length != 0);
				return c;
			}
		}
		return null;
	}
	
	@Override
	public int compareTo(com.alibaba.dubbo.remoting.buffer.ChannelBuffer arg0) {
		throw new java.lang.IllegalStateException();
	}

	@Override
	public int capacity() {
		throw new java.lang.IllegalStateException();
	}

	@Override
	public ChannelBuffer copy() {
		throw new java.lang.IllegalStateException();
	}

	@Override
	public ChannelBuffer copy(int index, int length) {
		throw new java.lang.IllegalStateException();
	}
	
	@Override
	public com.alibaba.dubbo.remoting.buffer.ChannelBufferFactory factory() {
		throw new java.lang.IllegalStateException();
	}

	
	@Override
	public byte[] array() {
		throw new java.lang.IllegalStateException();
	}

	@Override
	public boolean hasArray() {
		return false;
	}

	@Override
	public int arrayOffset() {
		return 0;
	}
}
